import 'dart:async';

import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';

import 'package:dmz/user/user_defurl.dart';
import 'package:dmz/user/user_model.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../base/controller/base_controller.dart';

class LoginPageController extends BaseController {
  //是否是验证码登录
  RxBool isCodeLG = true.obs;
  //是否隐藏密码
  RxBool obscureText = true.obs;
  //是否阅读隐私政策
  RxBool agreed = false.obs;

  Timer? timer;
  RxInt counter = 60.obs;
  RxInt snedCodeType = 0.obs;

  TextEditingController photneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController codeController = TextEditingController();

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  ///发送验证码
  snedCode() {
    if (snedCodeType.value == 1) return;
    if (!loginExamine(codeExamine: true)) return;
    startTimer();
    RequestClient().post(APIS.getCode, data: {'phone': photneController.text},
        onError: (error) {
      // debugPrint('sn验证4 -----${p0}');
      if (error.code != 0) {
        EMILoding.hitLoding('发送失败请稍后重试'.tr);
      }
      return false;
    }, onResponse: (p0) {
      debugPrint('sn验证3 -----${p0}');
    }).then((value) {
      debugPrint('sn验证3 -----${value}');
      EMILoding.hitLoding('发送成功'.tr, isScuess: true);
    });
  }

  ///登录
  login() {
    if (!loginExamine()) return;
    RequestClient().post<UserEntity>(APIS.login,
        data: !isCodeLG.value
            ? {
                'password': passwordController.text,
                'phone': photneController.text,
                'type': 0
              }
            : {
                'code': int.parse(codeController.text),
                'phone': photneController.text,
                'type': 1
              }, onError: (p0) {
      debugPrint('sn验证4 -----${p0}');
      return false;
    }, onResponse: (p0) {
      debugPrint('sn验证3 -----${p0}');
    }).then((value) {
      EMILoding.hitLoding('登录成功'.tr, isScuess: true);
      Get.offAllNamed(RouteGet.main);
      EMIBUserManger().saveToken(value?.token);
      if (value != null) EMIBUserManger().saveUser(value);
    });
  }

  void startTimer() {
    snedCodeType.value = 1;
    const oneSec = Duration(seconds: 1);
    timer = Timer.periodic(
      oneSec,
      (Timer timer) {
        if (counter.value == 0) {
          timer.cancel();
          counter.value = 60;
          snedCodeType.value = 2;
        } else {
          counter.value--;
        }
      },
    );
  }

  /// 输入框检查  codeExamine 验证码检验（只检验手机号）
  loginExamine({bool codeExamine = false}) {
    if (photneController.text.isEmpty) {
      EMILoding.hitLoding('手机号不能为空'.tr);
      return false;
    }
    if (codeExamine) return true;
    if (passwordController.text.isEmpty && !isCodeLG.value) {
      EMILoding.hitLoding('密码不能为空'.tr);
      return false;
    }

    if (codeController.text.isEmpty && isCodeLG.value) {
      EMILoding.hitLoding('验证码不能为空'.tr);
      return false;
    }

    if (!agreed.value) {
      EMILoding.hitLoding('同意用协议和隐私政策才能继续登录'.tr);
      return false;
    }

    return true;
  }

  showPrivacyPolicy(int type) {}

  turnFroeget() {
    Get.toNamed(RouteGet.password, arguments: true);
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }
}

class LoginBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => LoginPageController());
  }
}
